﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Maticsoft.DAL;
using System.Reflection;
using System.IO;

namespace BuildingForm.PersonInfo
{
    public partial class MonthStatistics : Form
    {
        public List<string> oldColsList = new List<string>();
        public List<string> newColsList = new List<string>();
        public string Title = string.Empty;
        //上个月某天到某天
        public string BeginDuration = string.Empty;
        //下个月某天到某天
        public string EndDuration = string.Empty;
        public MonthStatistics()
        {
            InitializeComponent();
             Init();
        }
 
        private void Init()
        {
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.ShowIcon = false;
            //表头加粗，居中
            foreach (DataGridViewColumn col in this.dataGridView1.Columns)
            {
                col.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("SimSun", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.dataGridView1.AllowUserToAddRows = false;
            //班组
            Maticsoft.DAL.Banz_Info info = new Banz_Info();
            DataTable dt = info.GetList("").Tables[0];
            List<string> strList = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                strList.Add(dt.Rows[i]["bzmc"].ToString().Trim());
            }
            List<string> list = new List<string>();
            list.Add("全部");
            list.AddRange(strList);
            this.cboTeam.DataSource = list;
            //年，月
            int[] months = new int[12] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
            this.cboMonth.DataSource = months;
            this.cboMonth.Text = DateTime.Now.Month.ToString();
            int year = DateTime.Now.Year;
            int[] years = new int[12] { year - 11, year - 10, year - 9, year - 8, year - 7, year - 6, year - 5, year - 4, year - 3, year - 2, year - 1, year };
            this.cboYear.DataSource = years;
            this.cboYear.Text = DateTime.Now.Year.ToString();
            //this.cboTeam.SelectedIndex = 1;
            LoadDays();
            this.cboDay.Text = "25";
        }
        public decimal TotalHours = 0;
        private List<MonthRecord> bind()
        {
            TotalHours = 0;
            Maticsoft.DAL.Kqjl_Info info = new Kqjl_Info();
            string sql = string.Empty;
            //DateTime beginT = Convert.ToDateTime(picBegin.Value);
            //DateTime endT = Convert.ToDateTime(picEnd.Value);
            int year = Convert.ToInt32(this.cboYear.Text.ToString());
            int month = Convert.ToInt32(this.cboMonth.Text.ToString());
            //string strT = year + "/" + month + "/" + "25";
            //DateTime endT = Convert.ToDateTime(strT).AddDays(1).AddMilliseconds(-1);
            //DateTime beginT = endT.AddMonths(-1).AddMilliseconds(1);
            int day = Convert.ToInt32(this.cboDay.Text.ToString());
            string strT = year + "/" + month + "/" + day;
            DateTime endT = Convert.ToDateTime(strT).AddDays(1).AddMilliseconds(-1);
            DateTime beginT = Convert.ToDateTime(strT).AddDays(1).AddMonths(-1).AddMilliseconds(1);

            sql = "CONVERT(varchar(10),a.kqsj,120)<='" + endT.ToString("yyyy-MM-dd") + "' and CONVERT(varchar(10),a.kqsj,120)>='" + beginT.ToString("yyyy-MM-dd") + "'";
            string team = this.cboTeam.Text.ToString().Trim();
            if (team != "全部")
            {
                sql += " and c.bzmc='" + team + "'";
            }
            sql += " order by a.sfzh,a.kqsj";
            DataTable dt = info.GetList3(sql).Tables[0];
            List<WorkTime> list = new List<WorkTime>();
            string sfzh_b = string.Empty;
            string dksj_b = string.Empty;
            DateTime beginTime = DateTime.MinValue;
            DateTime endTime = DateTime.MinValue;
            WorkTime arg = new WorkTime();
            int num = 1;
            decimal worktime = 0;
            //true进 false出
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                string sfzh_1 = dr["sfzh"].ToString();
                string dksj_1 = dr["dksj"].ToString();
                //if (sfzh_1 != "0566805022") continue;
                if (sfzh_b.Equals(sfzh_1) && dksj_b.Equals(dksj_1))
                {
                    bool isEnter = Convert.ToBoolean(dr["jczt"]);
                    //进
                    if (isEnter)
                    {
                        beginTime = Convert.ToDateTime(dr["kqsj"]);
                    }
                    else
                    {
                        if (endTime == DateTime.MinValue && beginTime != DateTime.MinValue)
                        {
                            endTime = Convert.ToDateTime(dr["kqsj"]);
                            TimeSpan ts = endTime - beginTime;
                            decimal di = ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds;
                            worktime += di;
                            //防止一个人一天的再次
                            beginTime = DateTime.MinValue;
                            endTime = DateTime.MinValue;
                        }
                    }

                }
                else
                {
                    if (i != 0)
                    {
                        //工时大于0的才记录,不能用worktime，几秒时就是0
                        decimal gs = Math.Round(worktime / 3600, 2);
                        if (gs > 0)
                        {
                            arg.gs = Math.Round(worktime / 3600, 2);
                            worktime = 0;
                            list.Add(arg);
                            TotalHours += gs;
                            num++;
                        }
                    }
                    //防止下一天或一个人的再次
                    beginTime = DateTime.MinValue;
                    endTime = DateTime.MinValue;
                    bool isEnter = Convert.ToBoolean(dr["jczt"]);
                    //进
                    if (isEnter)
                    {
                        beginTime = Convert.ToDateTime(dr["kqsj"]);
                    }

                    sfzh_b = sfzh_1;
                    dksj_b = dksj_1;
                    WorkTime w = new WorkTime();
                    w.xh = num;
                    w.xm = dr["xm"].ToString();
                    w.xb = dr["xb"].ToString();
                    w.gh = dr["gh"].ToString();
                    w.sfzh = dr["sfzh"].ToString();
                    w.bz = dr["bzmc"].ToString();
                    w.bzmc = dr["bzmc"].ToString();
                    w.gz = dr["gz"].ToString();
                    w.rq = Convert.ToDateTime(dksj_b);
                    arg = w;
                }
            }
            if (!string.IsNullOrEmpty(arg.sfzh))
            {
                arg.gs = Math.Round(worktime / 3600, 2);
                list.Add(arg);
            }
            List<MonthRecord> mList = ConvertMonthRecord(list);
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.DataSource = mList;
            return mList;
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                Sys_Info dao = new Sys_Info();
                string name = string.Empty;
                DataTable dtt = dao.GetList("").Tables[0];
                if (dtt.Rows.Count > 0)
                {
                    name = dtt.Rows[0]["gcmc"].ToString();
                }
                List<MonthRecord> list = bind();
                DataTable dt = ToDataSet(list).Tables[0];
                if (list==null)
                {
                    MessageBox.Show("没有数据！"); return;
                }
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                //设置文件类型   
                saveFileDialog1.Filter = " xls files(*.xls)|*.xls";
                //设置默认文件类型显示顺序   
                saveFileDialog1.FilterIndex = 2;
                //保存对话框是否记忆上次打开的目录   
                saveFileDialog1.RestoreDirectory = true;
                saveFileDialog1.FileName = "劳务人员月考勤表" + DateTime.Now.ToString("yyyyMMdd");
                //点了保存按钮进入   
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string team = this.cboTeam.Text.ToString().Trim();
                    if (team == "全部")
                    {
                        team = "所有人员";
                    }
                    GenerationColumns();
                    string fileName = saveFileDialog1.FileName;
                    //string[] oldCols = new string[] { "xh", "xm", "xb", "bz", "gz", "sfzh", "d26", "d27", "d28", "d29", "d30", "d31", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15", "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23", "d24", "d25", "dgs" };
                    //string[] newCols = new string[] { "编号", "工人姓名", "性别", "班组", "工种", "身份证号", "26", "27", "28", "29", "30", "31", " 1 ", " 2 ", " 3 ", " 4 ", " 5 ", " 6 ", " 7 ", " 8 ", " 9 ", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "出勤工时合计" };
                    string[] oldCols = oldColsList.ToArray();
                    string[] newCols = newColsList.ToArray();
                    ExcelHelper.ExportByEmployeeEntryExit3(dt, "劳务人员月考勤表", fileName, "Sheet1", oldCols, newCols, team + "," + this.cboYear.Text.ToString() + "," + this.cboMonth.Text.ToString()+","+name,Title,BeginDuration,EndDuration);
                    MessageBox.Show("导出文件成功！"); return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出文件故障！"); return;
            }
        }

        public static DataSet ToDataSet(IList p_List)
        {
            DataSet result = new DataSet();
            DataTable _DataTable = new DataTable();
            if (p_List.Count > 0)
            {
                PropertyInfo[] propertys = p_List[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    _DataTable.Columns.Add(pi.Name, pi.PropertyType);//columnName Type
                }

                for (int i = 0; i < p_List.Count; i++)
                {
                    ArrayList tempList = new ArrayList();    //一行数据的数组
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(p_List[i], null);//p_List[i]是集合中的某一个对象，GetValue 返回其属性值
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    _DataTable.LoadDataRow(array, true); //LoadDataRow 查找和更新特定行。 如果找不到任何匹配行，则使用给定值创建新行
                }
            }
            result.Tables.Add(_DataTable);
            return result;
        }
          
        private void button1_Click(object sender, EventArgs e)
        {
            bind();
        }
        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDays();
        }

        private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDays();
        }
        public void LoadDays()
        {
            if (!String.IsNullOrEmpty(this.cboYear.Text) && !String.IsNullOrEmpty(this.cboMonth.Text))
            {
                int yearNum = Convert.ToInt32(this.cboYear.Text);
                int monthNum = Convert.ToInt32(this.cboMonth.Text);
                int days = DateTime.DaysInMonth(yearNum, monthNum);
                List<int> dayList = new List<int>();
                for (var i = 1; i <= days; i++)
                {
                    dayList.Add(i);
                }
                this.cboDay.DataSource = dayList;
            }
        }
        
        public void GenerationColumns()
        {
            if (!String.IsNullOrEmpty(this.cboYear.Text) && !String.IsNullOrEmpty(this.cboMonth.Text))
            {
                oldColsList.Clear();
                newColsList.Clear();
                oldColsList.Add("xh");
                oldColsList.Add("xm");
                oldColsList.Add("xb");
                oldColsList.Add("bz");
                oldColsList.Add("gz");
                oldColsList.Add("sfzh");
                newColsList.Add("编号");
                newColsList.Add("工人姓名");
                newColsList.Add("性别");
                newColsList.Add("班组");
                newColsList.Add("工种");
                newColsList.Add("身份证号");
                int yearNum = Convert.ToInt32(this.cboYear.Text);
                int monthNum = Convert.ToInt32(this.cboMonth.Text);
                int dayNum = Convert.ToInt32(this.cboDay.Text);
               
                //int days = DateTime.DaysInMonth(yearNum, monthNum);

                string strT = yearNum + "/" + monthNum + "/" + dayNum;
                DateTime endT = Convert.ToDateTime(strT).AddDays(1).AddMilliseconds(-1);
                DateTime beginT = Convert.ToDateTime(strT).AddDays(1).AddMonths(-1).AddMilliseconds(1);
                if (beginT.ToString("yyyy-MM") == endT.ToString("yyyy-MM"))
                {
                    //查询一个月全部数据
                    Title = beginT.Month + "月";
                   // Title = Title.Replace("0", "");
                    for(var i = 1; i <= dayNum; i++)
                    {
                        oldColsList.Add("d" + i);
                        newColsList.Add(i.ToString());
                    }
                    BeginDuration = "1|" + dayNum;
                    EndDuration = "";

                }else
                {
                    //查询上个月某天到下个月某天
                    Title = beginT.Month+ "月|" + endT.Month + "月";
                   // Title = Title.Replace("0", "");
                    int days = DateTime.DaysInMonth(beginT.Year, beginT.Month);
                    for(var i = dayNum + 1; i <= days; i++)
                    {
                        oldColsList.Add("d" + i);
                        newColsList.Add(i.ToString());
                    }
                    for(var j = 1; j <= dayNum; j++)
                    {
                        oldColsList.Add("d" + j);
                        newColsList.Add(j.ToString());
                    }
                    BeginDuration = (dayNum + 1).ToString() + "|" + days;
                    EndDuration = "1|" + dayNum;
                }
                oldColsList.Add("dgs");
                newColsList.Add("出勤工时合计");
            }
        }
        public List<MonthRecord> ConvertMonthRecord(List<WorkTime> list)
        {
            if (list.Count == 0)
            {
                return null;
            }
            List<MonthRecord> mList = new List<MonthRecord>();
            MonthRecord obj = new MonthRecord();
            obj.sfzh = "";
            int k = 1;
            decimal dayGS = 0m;
            for (var i = 0; i < list.Count; i++)
            {
                if (obj.sfzh != list[i].sfzh)
                {
                    if (obj.sfzh != "")
                    {
                        obj.dgs = dayGS;
                        dayGS = 0m;
                        mList.Add(obj);
                        k++;
                    }
                    obj = new MonthRecord();
                    obj.bz = list[i].bz;
                    obj.gz = list[i].gz;
                    obj.gh = list[i].gh;
                    obj.sfzh = list[i].sfzh;
                    obj.xb = list[i].xb;
                    obj.xm = list[i].xm;
                    obj.xh = k;
                }
                int num = list[i].rq.Day;
                dayGS += list[i].gs;
                if (num == 1)
                {
                    obj.d1 = list[i].gs;
                }
                if (num == 2)
                {
                    obj.d2 = list[i].gs;
                }
                if (num == 3)
                {
                    obj.d3 = list[i].gs;
                }
                if (num == 4)
                {
                    obj.d4 = list[i].gs;
                }
                if (num == 5)
                {
                    obj.d5 = list[i].gs;
                }
                if (num == 6)
                {
                    obj.d6 = list[i].gs;
                }
                if (num == 7)
                {
                    obj.d7 = list[i].gs;
                }
                if (num == 8)
                {
                    obj.d8 = list[i].gs;
                }
                if (num == 9)
                {
                    obj.d9 = list[i].gs;
                }
                if (num == 10)
                {
                    obj.d10 = list[i].gs;
                }
                if (num == 11)
                {
                    obj.d11 = list[i].gs;
                }
                if (num == 12)
                {
                    obj.d12 = list[i].gs;
                }
                if (num == 13)
                {
                    obj.d13 = list[i].gs;
                }
                if (num == 14)
                {
                    obj.d14 = list[i].gs;
                }
                if (num == 15)
                {
                    obj.d15 = list[i].gs;
                }
                if (num == 16)
                {
                    obj.d16 = list[i].gs;
                }
                if (num == 17)
                {
                    obj.d17 = list[i].gs;
                }
                if (num == 18)
                {
                    obj.d18 = list[i].gs;
                }
                if (num == 19)
                {
                    obj.d19 = list[i].gs;
                }
                if (num == 20)
                {
                    obj.d20 = list[i].gs;
                }
                if (num == 21)
                {
                    obj.d21 = list[i].gs;
                }
                if (num == 22)
                {
                    obj.d22 = list[i].gs;
                }
                if (num == 23)
                {
                    obj.d23 = list[i].gs;
                }
                if (num == 24)
                {
                    obj.d24 = list[i].gs;
                }
                if (num == 25)
                {
                    obj.d25 = list[i].gs;
                }
                if (num == 26)
                {
                    obj.d26 = list[i].gs;
                }
                if (num == 27)
                {
                    obj.d27 = list[i].gs;
                }
                if (num == 28)
                {
                    obj.d28 = list[i].gs;
                }
                if (num == 29)
                {
                    obj.d29 = list[i].gs;
                }
                if (num == 30)
                {
                    obj.d30 = list[i].gs;
                }
                if (num == 31)
                {
                    obj.d31 = list[i].gs;
                }
            }
            obj.dgs = dayGS;
            mList.Add(obj);
            return mList;
        }

       
    }

    public class MonthRecord
    {
        public int xh { get; set; }
        public string xm { get; set; }
        public string sfzh { get; set; }
        public string gh { get; set; }
        public string bz { get; set; }
        public string gz { get; set; }
        public string xb { get; set; }
        //public DateTime rq { get; set; }
        //public decimal gs { get; set; }
        //public decimal dygs { get; set; }
        /// <summary>
        /// 该人员在上月26号到这个月25号的总工时
        /// </summary>
        public decimal dgs{get;set;}
        public decimal d26{get;set;}
         public decimal d27{get;set;}
         public decimal d28{get;set;}
         public decimal d29{get;set;}
         public decimal d30{get;set;}
         public decimal d31{get;set;}

         public decimal d1{get;set;}
         public decimal d2{get;set;}
         public decimal d3{get;set;}
         public decimal d4{get;set;}
         public decimal d5{get;set;}
         public decimal d6{get;set;}
         public decimal d7{get;set;}
         public decimal d8{get;set;}
         public decimal d9{get;set;}
         public decimal d10{get;set;}
         public decimal d11{get;set;}
         public decimal d12{get;set;}
         public decimal d13{get;set;}
         public decimal d14{get;set;}
         public decimal d15{get;set;}
         public decimal d16{get;set;}
         public decimal d17{get;set;}
         public decimal d18{get;set;}
         public decimal d19{get;set;}
         public decimal d20{get;set;}
         public decimal d21{get;set;}
         public decimal d22{get;set;}
         public decimal d23{get;set;}
         public decimal d24{get;set;}
         public decimal d25{get;set;}
    }
}
